﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Concurrency;
using System.Threading;
using System.Collections.Concurrent;

namespace ReactiveCode
{
    using Expressions;

    class StateChangeScheduler
    {
        #region Base scheduler

        IScheduler _scheduler, _defaultScheduler;
        internal IScheduler BaseScheduler
        {
            get { return _scheduler; }
            set { _scheduler = value ?? _defaultScheduler; }
        }

        StateChangeScheduler()
        {
            Contract.Requires(SynchronizationContext.Current != null);
            _scheduler = _defaultScheduler = new SynchronizationContextScheduler(SynchronizationContext.Current);
        } 

        #endregion

        #region Current

        [ThreadStatic]
        public static StateChangeScheduler _current;
        public static StateChangeScheduler Current
        {
            get { return _current ?? (_current = new StateChangeScheduler()); }
        }

        #endregion

        #region Notifications

        ConcurrentDictionary<ReactiveExpression, ConcurrentDictionary<object, Action>> _pendingNotifications = new ConcurrentDictionary<ReactiveExpression, ConcurrentDictionary<object, Action>>();
        void ScheduleNotification(ReactiveExpression expr, object stateIdentitiy, Action sendChange)
        {
            Contract.Requires(expr != null && stateIdentitiy != null && sendChange != null);

            var notifs = _pendingNotifications.GetOrAdd(expr, _ => new ConcurrentDictionary<object, Action>());
            notifs[stateIdentitiy] = sendChange;
            ScheduleSync();
        }
        public IObservable<T> Schedule<T>(IObservable<T> observable, ReactiveExpression expression)
        {
            return Observable.CreateWithDisposable<T>(o =>
            {
                var log = new LinkedList<Notification<T>>();
                return observable.Materialize().Subscribe(notif =>
                {
                    lock (log)
                    {
                        if (log.Last != null && !(notif is Notification<T>.OnError) && log.Last.Value.GetType() == notif.GetType())
                            log.Last.Value = notif;
                        else
                            log.AddLast(notif);
                    }
                    Action send = delegate
                    {
                        while (log.Count > 0)
                        {
                            Notification<T> notification;
                            lock (log)
                            {
                                notification = log.First.Value;
                                log.RemoveFirst();
                            }
                            notification.Accept(o);
                        }
                    };
                    if (log.Count == 1)
                        ScheduleNotification(expression, log, send);
                });
            });
        }

        #endregion

        #region State mutations

        ConcurrentQueue<Action> _pendingStateMutations = new ConcurrentQueue<Action>();
        public void ScheduleStateMutation(Action stateMutation)
        {
            Contract.Requires(stateMutation != null);

            _pendingStateMutations.Enqueue(stateMutation);
            ScheduleSync();
        }

        #endregion

        #region Sync

        bool _syncIsScheduled;
        void ScheduleSync()
        {
            if (_syncIsScheduled)
                return;
            _syncIsScheduled = true;
            BaseScheduler.Schedule(delegate
            {
                DoSyncCore();
                _syncIsScheduled = false;
            });
        }

        bool SendPendingNotification()
        {
            var expression = _pendingNotifications.ToArray()
                .Select(p => p.Key)
                .OrderBy(expr => expr, ReactiveExpression.OrderComparer)
                .FirstOrDefault();

            ConcurrentDictionary<object, Action> notifications;
            if (expression == null || !_pendingNotifications.TryRemove(expression, out notifications))
                return false;

            try
            {
                foreach (var notif in notifications.Values)
                    notif();
                return true;
            }
            catch
            {
                Debug.WriteLine("Sending notifications caused an exception.\nReceiver: {0}", expression);
                throw;
            }
        }
        void DoSyncCore()
        {
            Contract.Requires(this == Current);
            while (_pendingStateMutations.Count > 0 || _pendingNotifications.Count > 0)
            {
                Action mutation;
                while (_pendingStateMutations.TryDequeue(out mutation))
                    mutation();

                SendPendingNotification();
            }
        }

        public void DoSync()
        {
            Contract.Requires<InvalidOperationException>(this == Current, "DoSync is called on a thread that this StateChangeScheduler is not belonged to");
            bool syncWasScheduled = _syncIsScheduled;
            _syncIsScheduled = true;
            try
            {
                DoSyncCore();
            }
            finally
            {
                _syncIsScheduled = syncWasScheduled;
            }
        } 

        #endregion
    }
}
